<template>
  <div class="post-detail-page">
    <!-- 顶部导航栏 -->
    <header class="detail-header">
      <button class="back-btn" @click="goBack">← 返回</button>
      <h2 class="detail-title">帖子详情</h2>
      <div class="header-placeholder"></div>
    </header>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 帖子内容 -->
    <div v-else-if="post" class="post-detail-container">
      <!-- 作者信息 -->
      <div class="author-section">
        <img 
          :src="post.author?.avatar || '/default-avatar.png'" 
          :alt="post.author?.nickname"
          class="author-avatar-large"
        />
        <div class="author-info">
          <h3 class="author-name">{{ post.author?.nickname || '未知用户' }}</h3>
          <p class="post-time">{{ formatTime(post.created_at) }}</p>
        </div>
      </div>

      <!-- 帖子标题 -->
      <h1 class="detail-post-title">{{ post.title }}</h1>

      <!-- 帖子内容 -->
      <div class="detail-content" v-if="post.content">
        <p>{{ post.content }}</p>
      </div>

      <!-- 图片轮播 -->
      <div class="detail-images" v-if="post.images && post.images.length > 0">
        <div class="image-carousel">
          <div class="image-wrapper" ref="imageWrapperRef">
            <div 
              v-for="(image, index) in post.images" 
              :key="index"
              class="carousel-item"
              :class="{ active: currentImageIndex === index }"
            >
              <img 
                :src="image" 
                :alt="`${post.title} - 图片 ${index + 1}`"
                class="detail-image"
                @click="previewImage(index)"
              />
            </div>
          </div>
          
          <!-- 图片指示器 -->
          <div class="carousel-indicators" v-if="post.images.length > 1">
            <span 
              v-for="(image, index) in post.images" 
              :key="index"
              class="indicator"
              :class="{ active: currentImageIndex === index }"
              @click="switchImage(index)"
            ></span>
          </div>
          
          <!-- 左右切换按钮 -->
          <button 
            class="carousel-btn prev-btn" 
            @click="prevImage"
            v-if="post.images.length > 1"
          >
            ‹
          </button>
          <button 
            class="carousel-btn next-btn" 
            @click="nextImage"
            v-if="post.images.length > 1"
          >
            ›
          </button>
        </div>
      </div>

      <!-- 标签列表 -->
      <div class="detail-tags" v-if="post.tags && post.tags.length > 0">
        <span 
          v-for="tag in post.tags" 
          :key="tag"
          class="detail-tag"
          @click="handleTagClick(tag)"
        >
          #{{ tag }}
        </span>
      </div>

      <!-- 互动数据 -->
      <div class="detail-stats">
        <div class="stat-item">
          <span class="stat-icon">👁️</span>
          <span class="stat-value">{{ formatNumber(post.views) }}</span>
          <span class="stat-label">浏览</span>
        </div>
        <div class="stat-item">
          <span class="stat-icon">❤️</span>
          <span class="stat-value">{{ formatNumber(post.likes) }}</span>
          <span class="stat-label">点赞</span>
        </div>
        <div class="stat-item">
          <span class="stat-icon">💬</span>
          <span class="stat-value">{{ formatNumber(post.comments) }}</span>
          <span class="stat-label">评论</span>
        </div>
        <div class="stat-item">
          <span class="stat-icon">⭐</span>
          <span class="stat-value">{{ formatNumber(post.collects) }}</span>
          <span class="stat-label">收藏</span>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="detail-actions">
        <button class="action-button like-btn" @click="handleLike">
          <span class="icon">❤️</span>
          <span>{{ post.likes }}</span>
        </button>
        <button class="action-button comment-btn" @click="handleComment">
          <span class="icon">💬</span>
          <span>评论</span>
        </button>
        <button class="action-button collect-btn" @click="handleCollect">
          <span class="icon">⭐</span>
          <span>{{ post.collects }}</span>
        </button>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-state">
      <div class="error-icon">❌</div>
      <p class="error-message">{{ errorMessage || '帖子不存在或加载失败' }}</p>
      <button class="retry-btn" @click="fetchPostDetail">重试</button>
    </div>

    <!-- 图片预览模态框 -->
    <div v-if="showImagePreview" class="image-preview-modal" @click="closeImagePreview">
      <div class="preview-container">
        <img 
          :src="previewImageUrl" 
          class="preview-image"
          @click.stop
        />
        <button class="close-preview-btn" @click="closeImagePreview">×</button>
        <button 
          class="prev-preview-btn" 
          @click.stop="showPrevImage"
          v-if="post && post.images.length > 1"
        >
          ‹
        </button>
        <button 
          class="next-preview-btn" 
          @click.stop="showNextImage"
          v-if="post && post.images.length > 1"
        >
          ›
        </button>
        <div class="preview-counter" v-if="post && post.images.length > 1">
          {{ previewImageIndex + 1 }} / {{ post.images.length }}
        </div>
      </div>
    </div>

    <!-- 底部导航栏 -->
    <BottomNavigation />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import BottomNavigation from './BottomNavigation.vue'

const router = useRouter()
const route = useRoute()

// 响应式数据
const post = ref(null)
const loading = ref(false)
const errorMessage = ref('')
const showImagePreview = ref(false)
const previewImageIndex = ref(0)
const currentImageIndex = ref(0)  // 轮播当前索引
const imageWrapperRef = ref(null)

// 计算属性：预览图片URL
const previewImageUrl = computed(() => {
  if (post.value && post.value.images && post.value.images.length > 0) {
    return post.value.images[previewImageIndex.value]
  }
  return ''
})

// 获取帖子详情
const fetchPostDetail = async () => {
  const postId = route.params.id
  if (!postId) {
    errorMessage.value = '帖子ID无效'
    return
  }

  loading.value = true
  errorMessage.value = ''
  
  try {
    const url = `http://localhost:8000/api/posts/${postId}`
    console.log('[PostDetail] 请求URL:', url)
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    })
    
    console.log('[PostDetail] 响应状态:', response.status, response.statusText)
    
    if (!response.ok) {
      const errorText = await response.text()
      console.error('[PostDetail] 响应错误内容:', errorText)
      errorMessage.value = `获取帖子详情失败: ${response.status} ${response.statusText}`
      post.value = null
      return
    }
    
    const result = await response.json()
    console.log('[PostDetail] 响应数据:', result)
    
    // 后端现在直接返回帖子数据，不再有 {code, msg, data} 包装
    // 检查数据结构
    if (result && result.id) {
      post.value = result
      // 重置图片索引
      currentImageIndex.value = 0
      previewImageIndex.value = 0
    } else {
      errorMessage.value = '响应数据格式错误'
      post.value = null
    }
  } catch (error) {
    console.error('获取帖子详情失败:', error)
    // 添加更详细的错误提示
    if (error.message && (error.message.includes('Failed to fetch') || error.message.includes('NetworkError'))) {
      errorMessage.value = '无法连接到服务器，请检查：\n1. 后端服务器是否运行在 http://localhost:8000\n2. 网络连接是否正常'
    } else {
      errorMessage.value = `网络错误: ${error.message || '请检查连接'}`
    }
    post.value = null
  } finally {
    loading.value = false
  }
}

// 返回
const goBack = () => {
  router.back()
}

// 格式化数字
const formatNumber = (num) => {
  if (!num && num !== 0) return '0'
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'w'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now - date
  
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return date.toLocaleDateString('zh-CN')
}

// 图片轮播切换
const switchImage = (index) => {
  currentImageIndex.value = index
}

const nextImage = () => {
  if (post.value && post.value.images.length > 0) {
    currentImageIndex.value = (currentImageIndex.value + 1) % post.value.images.length
  }
}

const prevImage = () => {
  if (post.value && post.value.images.length > 0) {
    currentImageIndex.value = (currentImageIndex.value - 1 + post.value.images.length) % post.value.images.length
  }
}

// 点赞
const handleLike = () => {
  // TODO: 实现点赞功能
  console.log('点赞', post.value.id)
}

// 评论
const handleComment = () => {
  // TODO: 实现评论功能
  console.log('评论', post.value.id)
}

// 收藏
const handleCollect = () => {
  // TODO: 实现收藏功能
  console.log('收藏', post.value.id)
}

// 标签点击
const handleTagClick = (tag) => {
  // 可以跳转到标签筛选页面或触发筛选
  console.log('点击标签:', tag)
  // router.push(`/home?tag=${tag}`)
}

// 预览图片
const previewImage = (index) => {
  previewImageIndex.value = index
  showImagePreview.value = true
}

// 关闭预览
const closeImagePreview = () => {
  showImagePreview.value = false
}

// 预览上一张
const showPrevImage = () => {
  if (post.value && post.value.images.length > 0) {
    previewImageIndex.value = (previewImageIndex.value - 1 + post.value.images.length) % post.value.images.length
  }
}

// 预览下一张
const showNextImage = () => {
  if (post.value && post.value.images.length > 0) {
    previewImageIndex.value = (previewImageIndex.value + 1) % post.value.images.length
  }
}

// 组件挂载时加载数据
onMounted(() => {
  fetchPostDetail()
})
</script>

<style scoped>
.post-detail-page {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  background: #fff;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-sizing: border-box;
}

/* 顶部导航栏 */
.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-btn {
  background: none;
  border: none;
  font-size: 16px;
  color: #333;
  cursor: pointer;
  padding: 4px 8px;
  transition: color 0.2s;
}

.back-btn:hover {
  color: #ff2442;
}

.detail-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.header-placeholder {
  width: 60px;
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  color: #999;
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #ff2442;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 帖子详情容器 */
.post-detail-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px 16px 80px 16px;
  -webkit-overflow-scrolling: touch;
  max-width: 800px;
  margin: 0 auto;
  width: 100%;
}

/* 作者信息区域 */
.author-section {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.author-avatar-large {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
}

.author-info {
  flex: 1;
}

.author-name {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.post-time {
  margin: 0;
  font-size: 12px;
  color: #999;
}

/* 帖子标题 */
.detail-post-title {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin: 0 0 16px 0;
  line-height: 1.4;
}

/* 帖子内容 */
.detail-content {
  font-size: 16px;
  color: #666;
  line-height: 1.8;
  margin-bottom: 20px;
  white-space: pre-wrap;
}

/* 图片轮播 */
.detail-images {
  margin-bottom: 20px;
}

.image-carousel {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  background: #f5f5f5;
}

.image-wrapper {
  position: relative;
  width: 100%;
  padding-bottom: 75%; /* 4:3 比例 */
  overflow: hidden;
}

.carousel-item {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  transition: opacity 0.3s;
}

.carousel-item.active {
  opacity: 1;
}

.detail-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.3s;
}

.detail-image:hover {
  transform: scale(1.02);
}

/* 轮播指示器 */
.carousel-indicators {
  position: absolute;
  bottom: 12px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 8px;
  z-index: 10;
}

.indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.5);
  cursor: pointer;
  transition: all 0.3s;
}

.indicator.active {
  background: #fff;
  width: 20px;
  border-radius: 4px;
}

/* 轮播按钮 */
.carousel-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 40px;
  height: 40px;
  background: rgba(0, 0, 0, 0.3);
  border: none;
  border-radius: 50%;
  color: white;
  font-size: 24px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  transition: background 0.3s;
}

.carousel-btn:hover {
  background: rgba(0, 0, 0, 0.5);
}

.prev-btn {
  left: 12px;
}

.next-btn {
  right: 12px;
}

/* 标签 */
.detail-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 24px;
}

.detail-tag {
  font-size: 14px;
  color: #ff2442;
  background: #fff0f0;
  padding: 6px 12px;
  border-radius: 16px;
  cursor: pointer;
  transition: all 0.2s;
}

.detail-tag:hover {
  background: #ffe0e0;
  color: #e01d37;
}

/* 互动数据 */
.detail-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  padding: 16px 0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.stat-icon {
  font-size: 20px;
}

.stat-value {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.stat-label {
  font-size: 12px;
  color: #999;
}

/* 操作按钮 */
.detail-actions {
  display: flex;
  gap: 12px;
}

.action-button {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background: #fff;
  cursor: pointer;
  font-size: 14px;
  color: #333;
  transition: all 0.2s;
}

.action-button:hover {
  background: #f5f5f5;
  border-color: #ff2442;
  color: #ff2442;
}

.like-btn.active,
.collect-btn.active {
  background: #fff0f0;
  border-color: #ff2442;
  color: #ff2442;
}

/* 错误状态 */
.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  color: #999;
  padding: 40px;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.error-message {
  font-size: 16px;
  margin-bottom: 24px;
  text-align: center;
}

.retry-btn {
  padding: 10px 24px;
  background: #ff2442;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s;
}

.retry-btn:hover {
  background: #e01d37;
}

/* 图片预览模态框 */
.image-preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.95);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.preview-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.close-preview-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.2);
  border: none;
  border-radius: 50%;
  color: white;
  font-size: 28px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.3s;
}

.close-preview-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.prev-preview-btn,
.next-preview-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 50px;
  height: 50px;
  background: rgba(255, 255, 255, 0.2);
  border: none;
  border-radius: 50%;
  color: white;
  font-size: 32px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.3s;
}

.prev-preview-btn:hover,
.next-preview-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.prev-preview-btn {
  left: 20px;
}

.next-preview-btn {
  right: 20px;
}

.preview-counter {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 14px;
}

/* 响应式 */
@media (max-width: 768px) {
  .post-detail-container {
    padding: 16px 12px 80px 12px;
  }

  .detail-post-title {
    font-size: 20px;
  }

  .image-wrapper {
    padding-bottom: 100%; /* 移动端 1:1 */
  }
}
</style>

